package com.ces.knacky.controller.buynsell;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ces.knacky.framework.controller.ListController;
import com.ces.knacky.services.CheckoutService;
@Controller
public class CheckoutController<OrderItem> extends ListController<OrderItem> {
	
	@Autowired
	private CheckoutService checkoutService;
	/**
	 * Comma separated list of Item ids selected from the JSP page.
	 */
	private String selectedIds;	
	
	@RequestMapping("/buyNow.htm") 
	public String execute(HttpServletRequest request) {
		Integer entityId = checkoutService.placeOrder(selectedIds);
		if (entityId != null) {
			HttpSession session = request.getSession(true);
			session.setAttribute("orderCart", entityId);
		}
		return "buyNow";
	}
	/**
	 * This method is used to return comma separated list of Item ids selected by the user.
	 * 
	 * @return 	String
	 * 			Represents comma separated list of Item ids selected by the user.
	 */
	public String getSelectedIds() {
		return selectedIds;
	}

	/**
	 * It is used to set/map the ids selected by the user.
	 *  
	 * @param 	selectedIds
	 * 			Represents comma separated list of Item ids selected by the user.
	 */
	@ModelAttribute("selectedIds")
	public void setSelectedIds(String selectedIds) {
		this.selectedIds = selectedIds;
	}
	/**
	 * @return the checkoutService
	 */
	public CheckoutService getCheckoutService() {
		return checkoutService;
	}
	/**
	 * @param checkoutService the checkoutService to set
	 */
	public void setCheckoutService(CheckoutService checkoutService) {
		this.checkoutService = checkoutService;
	}
	/**
	 * It is used to fetch items whose order is placed during a user session.
	 * 
	 * @param 	request
	 * 			HttpServletRequest object to fetch session and then the orderId.
	 * @return	String
	 * 			Represents view resolver.
	 */
	@RequestMapping("/showOrderPlaced.htm") 
	public String showOrderPlaced(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		Integer orderId = (Integer)session.getAttribute("orderCart");
		if(orderId != null){
			listEntity = (List<OrderItem>) checkoutService.fetchPlacedOrder(
					SecurityContextHolder.getContext().getAuthentication().getName(), orderId);
		}
		return "showOrderPlaced";
	}
}
